package cn.cosmosx.base.hook;

import cn.cosmosx.base.constant.GlobalConstant;
import cn.cosmosx.base.helper.SpringContextHolder;
import cn.cosmosx.base.id.IDGenerator;
import cn.cosmosx.base.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 自定义的资源释放钩子
 */
@Slf4j
@Component
public class QsShutDownHookManager implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
        log.info("Initialize QsShutDownHookManager");
        // 注册钩子，程序停止时释放资源
        Runtime.getRuntime().addShutdownHook(new ApplicationExit("QsShutDownHookManager"));
    }

    private static class ApplicationExit extends Thread {
        ApplicationExit(String threadName) {
            super(threadName);
        }

        @Override
        public void run() {
            RedisService redisService = SpringContextHolder.getBean(RedisService.class);
            // 持久化全局流水号
            IDGenerator.persist(redisService);
            // 释放Redis资源
            log.warn("===============================================================");
            log.warn("release redis resources...");
            log.warn("like keys prefix:{}", GlobalConstant.PERMISSIONS);
            redisService.deleteLike(GlobalConstant.PERMISSIONS);
            log.warn("like keys prefix:{}", GlobalConstant.AccessKey);
            redisService.deleteLike(GlobalConstant.AccessKey);
            log.warn("like keys prefix:{}", GlobalConstant.ENCRYPT_TOKEN);
            redisService.deleteLike(GlobalConstant.ENCRYPT_TOKEN);
            log.warn("===============================================================");
        }
    }
}
